<template>
  <div class="chat-content-wrap">
    <div class="history-wrap">
      <!--正在对话-->
      <div v-if="chatHistory.length">
        <!--ai回答-->
        <div v-for="(item,idx) in chatHistory">
          <!--普通对话-->
          <div v-if="item.msgType == '2' || item.msgType == '4'">
            <div class="left-person">
              <div class="left-img">
                <img src="../../assets/image/aichat/aiRobot.png">
              </div>
              <!--加载中-->
              <div class="right-info">
                <div class="text-bold">制度检索小助手</div>
              </div>
            </div>
            <div class="ai-reply">
              <!--<div class="time">{{item.startTime}}</div>-->
              <div>
                <div v-if="submitFlag && idx==chatHistory.length-1"
                     v-html="printedText"></div>
                <div v-else v-html="item.content"></div>
              </div>
            </div>
          </div>
          <!--用户输入相关文字-->
          <div class="right-person" v-if="item.msgType == '3'">
            <div class="wenzi">
              <div class="bubble">
                <div class="title">{{ item.content }}</div>
              </div>
            </div>
          </div>
          <!--ai回答 -->
          <div v-if="item.msgType == '100'">
            <div v-if="!item.show">
              <div class="left-person">
                <div class="left-img">
                  <img src="../../assets/image/aichat/aiRobot.png">
                </div>
                <!--加载中-->
                <div class="right-info">
                  <div class="text-bold">制度检索小助手</div>
                </div>
              </div>
              <div class="ai-reply">
                <div class="padding" v-if="submitFlag && idx == chatHistory.length-1 && printedText">
                  <!--文字-->
                  <div v-html="renderedMarkdown(printedText)"></div>
                  <!-- 卡片处理状态-->
                  <div class="card-loading" element-loading-text="加载中，请稍等..." v-show="item.loading"
                       v-loading="item.loading"></div>
                </div>
                <div class="show-chat padding-sm" v-else>
                  <img style="width: 20px; height: 20px;" src="../../assets/image/common/load.gif"/>
                  <span class="show-chat-tip" v-for="(text,index) in showChatTip"
                        :style="'--i:' + (index+1)">{{ text }}</span>
                </div>
              </div>
            </div>
            <!--回答完毕显示卡片-->
            <div v-if="item.show">
              <div v-if="item.details.result1?.files>0">
                <div class="left-person">
                  <div class="left-img">
                    <img src="../../assets/image/aichat/aiRobot.png">
                  </div>
                  <!--加载中-->
                  <div class="right-info">
                    <div class="text-bold">制度检索小助手</div>
                  </div>
                </div>
                <!--加载完毕-->
                <div class="ai-reply" v-if="item.details">
                  <!--ai回复盒子-->
                  <div class="padding text-171717">
                    <div>
                      <div class="header-box flex align-center">
                        <img width="27" height="27" src="../../assets/image/aichat/title-icon.png"/>
                        <div class="text margin-left-xs">检索结果总结</div>
                      </div>
                      <div class="padding-left">
                        <el-row class="padding-top-lg">
                          <el-col :span="8">
                            涉及地市：{{ item.details.result1.citys.length ? item.details.result1.citys.join('、') : '' }}
                          </el-col>
                          <el-col :span="8">
                            发布时间：{{ item.details.result1?.times }}
                          </el-col>
                        </el-row>
                        <el-row class="padding-top-8">
                          <el-col :span="16">
                            涉及文件数：{{ item.details.result1?.files }}
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                    <div>
                      <div class="flex padding-top-xl align-center padding-left">
                        <img width="27" height="27" src="../../assets/image/aichat/title-icon.png"/>
                        <div class="text margin-left-xs">对比情况</div>
                      </div>
                      <div class="padding-top-sm padding-left">
                        {{ item.details.result2?.between }}
                      </div>
                    </div>
                    <div class="padding-top-sm padding-bottom-sm min-height padding-left padding-right">
                      <div class="text-232323 text-bold padding-top-sm">目标原文</div>
                      <div class="padding-sm margin-top bg-F0F7FF relative"
                           v-for="(item2,index) in item.details.result3?.original">
                        <div>
                          <div v-html="item2.content"></div>
                        </div>
                        <div class="absolute bg-white text-blue text-center padding-top-xs padding-bottom-xs">
                          <el-popover
                              placement="bottom-end"
                              :width="450"
                              trigger="hover"
                          >
                            <el-row>
                              <el-col :span="24" class="text-bold">{{ item2.filename }}</el-col>
                              <el-col class="padding-top-4" :span="12">
                                区域： {{ item2.city }}
                              </el-col>
                              <el-col class="padding-top-4" :span="12">
                                部门： {{ item2.department }}
                              </el-col>
                              <el-col class="padding-top-4" :span="12">发布时间：{{ item2.time }}</el-col>
                              <template v-if="item2.moreInfo">
                                <el-col class="padding-top-4" :span="12">联系人：
                                  <a :class="item2.moreInfo['compiler']? 'text-blue' : ''">
                                    <span>{{ item2.moreInfo['compiler'] || "无" }}</span>
                                    <span class="padding-left-xs">{{ item2.moreInfo['creator'] }}</span>
                                  </a>
                                </el-col>
                                <el-col class="padding-top-4" :span="24">
                                  相关联的上级公司制度：
                                  <template v-if="item2.moreInfo['associatedSuperiorCompanySystem']===true">是
                                  </template>
                                  <template v-else-if="item2.moreInfo['associatedSuperiorCompanySystem']===false">否
                                  </template>
                                  <template v-else>无</template>
                                </el-col>
                                <el-col class="padding-top-4" :span="24">
                                  是否明确要求下级公司二次细化本制度：
                                  <template
                                      v-if="item2.moreInfo['whetherRequireSecondaryRefinementFromSubCompanies']===true">
                                    是
                                  </template>
                                  <template
                                      v-else-if="item2.moreInfo['whetherRequireSecondaryRefinementFromSubCompanies']===false">
                                    否
                                  </template>
                                  <template v-else>无</template>
                                </el-col>
                                <el-col class="padding-top-4" :span="24">
                                  <div class="flex">
                                    <span> 下载链接：</span>
                                    <a :class="item2.moreInfo['downloadLink']? 'text-blue' : ''" style="width: 350px"
                                       :href="item2.moreInfo['downloadLink']"
                                       target="_blank">
                                      {{ item2.moreInfo['downloadLink'] || '无' }}
                                    </a>
                                  </div>

                                </el-col>
                              </template>
                            </el-row>
                            <template #reference>
                              <div class="pointer" @mouseenter="loadMore(idx,index,item2)">
                                <span class="iconfont lianjie1"></span>来源
                              </div>
                            </template>
                          </el-popover>
                        </div>
                      </div>
                    </div>

                  </div>
                  <div class="right-img"></div>
                </div>
              </div>
              <div v-else>
                <div class="left-person">
                  <div class="left-img">
                    <img src="../../assets/image/aichat/aiRobot.png">
                  </div>
                  <!--加载中-->
                  <div class="right-info">
                    <div class="text-bold">制度检索小助手</div>
                  </div>
                </div>
                <!--加载完毕-->
                <div class="ai-reply" style="width: 180px">
                  <div class="padding-sm">
                    <div class="show-chat">
                      暂未搜索到相关制度
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
        <!--正在加载ai回答-->
        <div v-if="showChatLoading">
          <div class="left-person">
            <div class="left-img">
              <img src="../../assets/image/aichat/aiRobot.png">
            </div>
            <!--加载中-->
            <div class="right-info">
              <div class="text-bold">制度检索小助手</div>
            </div>
          </div>
          <div class="ai-reply flex align-center" style="width: 160px">
            <div class="padding-sm">
              <div class="show-chat">
                <img style="width: 20px; height: 20px;" src="../../assets/image/common/load.gif"/>
                <span class="show-chat-tip" v-for="(text,index) in showChatTip"
                      :style="'--i:' + (index+1)">{{ text }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--没有过对话-->
      <div v-else class="no-chat">
        <div>
          <div class="text">
            <span class="text-24">您好</span>
            <span>
                  , 我是您的制度检索Al小助手
                </span>
          </div>
          <div class="text-3E3E3E padding-top-xs text-sm">
            汇集移动内部全量制度，支持按地市、部门检索制度，可对不同地市不同部门的制度内容进行比较
          </div>
          <el-row class="padding-tb-xl">
            <el-col :span="20">
              <ul class="grid col-3">
                <li>
                  <div class="margin-xs tip-item item1 text-center flex align-center">
                    <img src="../../assets/image/aichat/tip-icon1.png">
                    <div class="padding-left"> 搜索对应地市制度</div>
                  </div>
                </li>
                <li>
                  <div class="margin-xs tip-item item2 text-center flex align-center">
                    <img src="../../assets/image/aichat/tip-icon2.png">
                    <div class="padding-left"> 搜索对应部门制度</div>
                  </div>
                </li>
                <li>
                  <div class="margin-xs tip-item item3 text-center flex align-center">
                    <img src="../../assets/image/aichat/tip-icon3.png">
                    <div class="padding-left"> 比较不同地市制度</div>

                  </div>
                </li>
              </ul>
            </el-col>
          </el-row>
          <el-row class="">
            <el-col :span="18">
              <ul class="grid col-3 text-sm">
                <li @click="tipClick(0)" class="pointer">
                  <div class="margin-xs tip2-item bg-white text-center flex align-center">
                    <div class="padding-left"> 搜索常州的号卡管理制度</div>
                  </div>
                </li>
                <li @click="tipClick(1)" class="pointer">
                  <div class="margin-xs tip2-item bg-white  text-center flex align-center">
                    <div class="padding-left"> 帮我比较常州和盐城商机管理制度</div>
                  </div>
                </li>
                <li @click="tipClick(2)" class="pointer">
                  <div class="margin-xs  tip2-item bg-white text-center flex align-center">
                    <div class="padding-left"> 搜索省公司和盐城的商机更新制度</div>
                  </div>
                </li>
              </ul>
            </el-col>
          </el-row>
        </div>
        <div class="right-img"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {defineEmits, defineExpose, defineProps, getCurrentInstance, nextTick, onMounted, ref, watch} from 'vue'
//引入相关样式
import '@vue-office/docx/lib/index.css'
import {removeLastHash} from "@/utils/index.js";
import axios from "axios";
import {dateFormat} from "@/base/utils.js";
import aiJson from "@/pages/aiJson"

let json1 = aiJson.json1

let json2 = aiJson.json2

let json3 = aiJson.json3

let props = defineProps(['chatHistory', 'showChatLoading', 'showChatTip', 'submitFlag', '', 'fullScreen']);
let emit = defineEmits(['resetSubmit', 'resetScroll', 'update:chatHistory']);

const {proxy} = getCurrentInstance()
const apiBaseUrl = import.meta.env.VITE_APP_ZUUL_PATH2; // 获取 代理地址 对应的值
const apiBaseUrl1 = import.meta.env.VITE_APP_ZUUL_PATH3; // 获取 代理地址 对应的值
// 聊天记录list
// const chatHistory = ref([])
let fileField = ref({
  "头文件名": "fileHeaderName",
  "下载链接": "downloadLink",
  "下载位置": "downloadLocation",
  "文件大小": "fileSize",
  "是否成功": "isSuccess",
  "下载时间": "downloadTime",
  "文档名称": "documentName",
  "区域": "region",
  "部门": "department",
  "使用状态": "usageStatus",
  "CREATOR": "creator",
  "编撰人": "compiler",
  "相关联的上级公司制度": "associatedSuperiorCompanySystem",
  "是否明确要求下级公司二次细化本制度": "whetherRequireSecondaryRefinementFromSubCompanies",
  "resource_id": "resourceId"
})// 文件字段映射
// 打印文字
const printedText = ref('');
watch(() => printedText.value, () => {
  nextTick(() => {
    const aTags = document.querySelectorAll('a');
    // 遍历所有的 a 标签
    aTags.forEach((link) => {
      if (link.href.startsWith('http') || link.href.startsWith('https')) {
        link.target = '_blank';
      }
    });
  })

}, {immediate: true})

const tipClick = (index) => {
  emit('tipClick', index)
}
// 开始打字
const printText = (textToPrint) => {
  printedText.value = ''
  const printInterval = setInterval(() => {
    if (printedText.value.length < textToPrint.length) {
      printedText.value += textToPrint[printedText.value.length];
    } else {
      emit('resetSubmit')
      clearInterval(printInterval);
    }
    emit('resetScroll')
  }, 10); // 每0.5秒打印一个字符
}

const printStreamText = async (textToPrint, printFlag, pauseFlag = false) => {
  if (printFlag == 'begin') {

  } else if (printFlag == 'end') {
    printedText.value = await removeLastHash(printedText.value)
    // 是否中断回答的打印
    if (!pauseFlag) {
      let id = new Date().getTime()
      // 设置props.chatHistory最后一项的loading是加载中状态
      let item = {
        'id': id,
        'startTime': dateFormat(new Date(), 'MM-dd hh:mm'),
        'msgType': '100',
        'show': false,
        'content': printedText.value,
        'loading': true,
      }
      emit('resetScroll')
      let list = props.chatHistory
      list[list.length - 1] = item
      item.details = await parseText(printedText.value)
      item.loading = false
      item.show = true
      list[list.length - 1] = item
    }
    printedText.value = ""
  }
  printedText.value += textToPrint
  emit('resetScroll')
}
const renderedMarkdown = (content) => {
  return content
}


// 定义 parse_ai_response 函数
function parse_ai_response(response_text) {
  if (!response_text) {
    return null;
  }

  const parseStrategies = [
    (x) => JSON.parse(x), // 直接解析
    (x) => JSON.parse(x.split('|')[1].trim()), // 解析管道内的JSON
    (x) => JSON.parse(x.split("```json")[1].split("```")[0].trim()), // 解析代码块内的JSON
    (x) => JSON.parse(x.replace(/\n/g, '').replace(/\\/g, '').trim()) // 清理后解析
  ];

  for (const strategy of parseStrategies) {
    try {
      return strategy(response_text);
    } catch (error) {
      if (error instanceof SyntaxError || error instanceof TypeError) {
        continue;
      }
      throw error;
    }
  }

  return null;
}


const parseText = async (text) => {
  // 定义请求的 URL
  const url = `${apiBaseUrl}/nl/chat/completions`;

  // 创建请求配置的工厂函数
  const createRequestOptions = (prompt) => ({
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      'AI-API-CODE': 'wif9hhnFEO',
      'AI-APP-KEY': 'VCRZouogAZ'
    },
    body: JSON.stringify({
      stream: false,
      model: 'qwen2.5_72B_nl',
      messages: [
        {role: 'system', content: prompt},
        {role: 'user', content: text}
      ]
    })
  });

  // 创建单个请求的处理函数
  const makeRequest = async (prompt) => {
    try {
      const response = await fetch(url, createRequestOptions(prompt));
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      return parse_ai_response(data.choices[0].message.content)
    } catch (error) {
      console.error('Fetch error:', error);
      return null;
    }
  };

  try {
    // 同时发起所有请求
    const [result1, result2, result3] = await Promise.all([
      makeRequest(json1, 'wif9hhnFEO', 'qwen2.5_72B_nl', url),
      makeRequest(json2, 'wif9hhnFEO', 'qwen2.5_72B_nl', url),
      makeRequest2(printedText.value),
    ]);
    console.info('结果1 (涉及地市等信息):', result1);
    console.info('结果2 (对比情况):', result2);
    console.info('结果3 (对比情况):', result3);

    return {
      result1: result1,
      result2: result2,
      result3: result3,
    };
  } catch (error) {
    console.error('Error in parallel requests:', error);
  }
};
const makeRequest2 = async (text) => {
  // 定义请求的 URL
  const url = `${apiBaseUrl}/ml/chat/completions`;
  // 定义请求的选项
  const options =
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'AI-API-CODE': 'LYXmWuCqzs',
          'AI-APP-KEY': 'VCRZouogAZ'
        },
        body: JSON.stringify({
          stream: false,
          model: 'qwen2.5_14B_nl',
          messages: [
            {role: 'system', content: json3},
            {role: 'user', content: text}
          ]
        })
      };


  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return parse_ai_response(data.choices[0].message.content)
  } catch (error) {
    console.error('Fetch error:', error);
    return null;
  } finally {

  }
};
let ctrl = null
// 鼠标进入加载更多
const loadMore = async (fIndex, sIndex, sItem) => {
  // 没有加载过文件详细信息并且文件名称存在
  if (!sItem.moreInfo && sItem.filename) {
    // 定义请求的 URL
    const url = `${apiBaseUrl1}/regulations/query_file_info`;
    let headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "AuthToken": "72201b76431142f99804e21d00a2bde2"
    }

    let data = {
      "fileName": sItem.filename,
      // "requestId": new Date() + '000',
      // yyyymmddhhmmssSSS000111
      // "dialogld": moment().format('YYYYMMDDHHmmssSSS') + "000111"
    }

    const response = await axios.post(url, data, {headers});
    console.info('responseData', response.data)

    if (response && response.data && response.data.length) {
      const responseData = JSON.parse(response.data);
      // sItem.fileInfo = responseData.data.data[0];
      console.info('responseData', responseData)
      // 处理一下更多信息
      sItem.moreInfo = responseData.data
      console.info('sItem.moreInfo', sItem.moreInfo)
      // 更新一下父组件的对话列表
      let list = props.chatHistory
      list[fIndex]['details']['result3'][sIndex] = sItem
    } else {
      sItem.moreInfo = []
    }
  }
}

// 子组件默认包含是私有
defineExpose({
  printStreamText,
  printedText,
})

onMounted(() => {
  // loadMore(1, 1, {filename: '《中国移动常州分公司社会实体渠道管理办法（2024年版）.docx'})
})
</script>

<style scoped lang="less">
.chat-content-wrap {
  .history-wrap {
    overflow: hidden;
    padding-bottom: 10px;


    .left-person {
      width: 100%;
      display: flex;
      //align-items: center;
      margin-bottom: 15px;

      .left-img {
        img {
          width: 36px;
          padding-top: 3px;
        }

      }

      .right-info {
        margin-left: 8px;
        margin-top: 5px;

      }
    }

    .right-person {
      margin-bottom: 20px;
      width: 100%;
      overflow: hidden;

      .wenzi {
        text-align: left;
        margin-right: 10px;
        display: block;
        float: right;

        .bubble {
          padding: 10px 12px;
          margin-top: 6px;
          display: inline-block;
          min-width: 16px;
          float: right;
          background: #768EDF url("../../assets/image/aichat/sun.png") no-repeat left -120px top -50px;
          background-repeat: no-repeat;
          border-radius: 8px 0 8px 8px;
          word-break: break-all;
          max-width: calc(90vw - 125px);
          letter-spacing: 1px;
          color: #FFFFFF;

          .title {
            line-height: 18px;
            font-size: 14px;
          }
        }

        ::v-deep .bubble-full {
          max-width: calc(50vw - 125px);
        }
      }

    }

    .ai-reply {
      background-color: white;
      width: calc(100vw - 500px);
      position: relative;
      border-radius: 4px;

      .content-text {
        padding: 10px 20px;
        font-size: 14px;
        /*line-height: 20px;*/
        /*white-space: pre-line;*/
        word-break: break-all;
        word-wrap: break-word;

      }

      .text {
        color: #3F61A4;
      }

      .card-loading {
        height: 80px;
        padding-bottom: 20px;
      }

      .header-box {
        background: url("../../assets/image/aichat/replay-bg.png");
        padding: 7px 15px;
        background-size: cover;
      }

      .right-img {
        position: absolute;
        top: 10px;
        right: 20px;
        height: 132px;
        width: 132px;
        background: url("../../assets/image/aichat/replay-icon.png") no-repeat 95% center;
        background-size: 132px 132px;
      }
    }

  }

  /* 美化整个滚动条 */

  ::-webkit-scrollbar {
    width: 8px; /* 设置滚动条的宽度 */
    background-color: #f9f9f9; /* 滚动条的背景色 */
  }

  /* 美化滚动条轨道 */

  ::-webkit-scrollbar-track {
    background: #FFFFFF; /* 轨道的背景色 */
  }

  /* 美化滚动条的滑块 */

  ::-webkit-scrollbar-thumb {
    background-color: #c1c1c1; /* 滑块的背景色 */
    border-radius: 10px; /* 滑块的圆角 */
    border: 2px solid #ffffff; /* 滑块边框 */
  }

  /* 当滑块悬停或活动时的样式 */

  ::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8; /* 悬停或活动状态下的背景色 */
  }

  ::v-deep .el-dialog {
    --el-dialog-margin-top: 10vh !important;
  }
}

.bg-F0F7FF {
  border-radius: 8px;
  background-color: #F0F7FF;

  .absolute {
    right: 0;
    top: 0;
    width: 68px;
    border-radius: 0px 8px 0px 17px;
  }
}

.no-chat {
  background: url("../../assets/image/aichat/tip-bg.png") no-repeat;
  background-size: 101% 100%;
  padding: 18px;
  margin: 25px;

  .text {
    /* 设置渐变背景 */
    background: linear-gradient(134.55175955168357deg, #53E8B9 0%, #48AFBC 24%, #4EA8BE 43%, #6CA7DB 68%, #78A4E8 83%, #6B77D6 100%); /* 将背景裁剪为文字的形状 */
    -webkit-background-clip: text;
    /* 文本颜色设置为透明，这样就会显示出背景的渐变效果 */
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    -moz-background-clip: text;
    -moz-text-fill-color: transparent;
    -ms-background-clip: text;
    -ms-text-fill-color: transparent;
    background-clip: text;
    text-fill-color: transparent;
  }

  .right-img {
    position: absolute;
    top: 30px;
    right: 50px;
    width: 254px;
    height: 225px;
    background: url("../../assets/image/aichat/tip-right.png") no-repeat;
    background-size: cover;
  }

  .tip-item {
    padding: 15px 11px;
    font-size: 16px;
    box-shadow: 0px 10px 12px 0px rgba(235, 240, 243, 0.39);
    border-radius: 8px;
    border: 1px solid #FFFFFF;
  }

  .item1 {
    background: #E3F4FF;
    color: #0066D4;
  }

  .item2 {
    background: #E7F3E9;
    color: #248124;
  }

  .item3 {
    background: #F0EEF6;
    color: #56368F;
  }

  .tip2-item {
    padding: 5px 14px;
    border-radius: 2px;
  }
}

.min-height {
  //min-height: 200px;
}
.padding-top-8{
  padding-top: 8px;
}
.show-chat {
  display: flex;
  align-items: center; /* 垂直居中对齐 */

  .show-chat-tip {
    font-size: 14px;
    color: #666060;
    /* 添加动画 */
    animation: bounce 1.5s ease-in-out infinite;
    /* 利用变量动态计算动画延迟时间 */
    animation-delay: calc(.1s * var(--i));
  }
}

</style>
